import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';

// 服务和策略
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';

// 守卫
import { JwtAuthGuard } from './guards/jwt-auth.guard';

/**
 * 认证模块 - 零隐患MFIS规范
 * 解决隐患：#15 密钥管理，#2 异常处理
 */
@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.registerAsync({
      imports: [],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET'),
        signOptions: {
          expiresIn: configService.get<string>('JWT_EXPIRES_IN', '2h'),
          issuer: 'uc-system',
          audience: 'uc-system-client',
        },
        verifyOptions: {
          issuer: 'uc-system',
          audience: 'uc-system-client',
        },
      }),
      inject: [ConfigService],
    }),
  ],
  providers: [
    AuthService,
    JwtStrategy,
    LocalStrategy,
    JwtAuthGuard,
  ],
  exports: [
    AuthService,
    JwtModule,
    JwtAuthGuard,
  ],
})
export class AuthModule {
  constructor(private readonly configService: ConfigService) {
    // 验证JWT配置
    this.validateJwtConfiguration();
  }

  private validateJwtConfiguration(): void {
    const jwtSecret = this.configService.get<string>('JWT_SECRET');

    if (!jwtSecret) {
      console.error('🚨 CRITICAL: JWT_SECRET 未配置');
      process.exit(1);
    }

    if (jwtSecret.length < 32) {
      console.error('🚨 CRITICAL: JWT_SECRET 长度必须至少32字符');
      process.exit(1);
    }

    console.log('✅ JWT配置验证通过');
  }
}